package com.baidu.fsg.uid.config;

import com.baidu.fsg.uid.IdMappingService;
import com.baidu.fsg.uid.impl.IdMappingServiceImpl;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.json.ReaderBasedJsonParser;
import com.fasterxml.jackson.core.json.UTF8StreamJsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.util.List;

public class IdMappingDeserialize extends JsonDeserializer<Object> {

  IdMappingService idMappingService;
  public IdMappingDeserialize(){
    this.idMappingService = IdMappingServiceImpl.getIdMappingService();
  }
  @Override
  public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    if(IdMappingDisableConfiguration.isDisable.get() != null && IdMappingDisableConfiguration.isDisable.get()){
      if(p instanceof ReaderBasedJsonParser){
        List<String> uuids = p.readValueAsTree();
        return uuids;
      }else  if(p instanceof UTF8StreamJsonParser){
        UTF8StreamJsonParser utf8StreamJsonParser = (UTF8StreamJsonParser) p;
        utf8StreamJsonParser.finishToken();
        String value = utf8StreamJsonParser.getText();
        return value;
      }
      return null;
    }
    if(p instanceof ReaderBasedJsonParser){
      List<String> uuids = p.readValueAsTree();
      return idMappingService.getId(uuids);
    }else if(p instanceof UTF8StreamJsonParser){
      UTF8StreamJsonParser utf8StreamJsonParser = (UTF8StreamJsonParser) p;
      utf8StreamJsonParser.finishToken();
      String value = utf8StreamJsonParser.getText();
      String id = idMappingService.getId(value);
      return id;
    }
    return null;
  }
}
